<template>
  <div class="benefit-usage-container">
    <div class="header">
      <h2>会员权益使用记录</h2>
      <div class="header-actions">
        <el-button @click="exportData" type="primary" icon="el-icon-download">导出数据</el-button>
        <el-button @click="refreshData" icon="el-icon-refresh">刷新</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-s-data"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.totalUsage || 0 }}</h3>
          <p>总使用次数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-user"></i>
        </div>
        <div class="stat-content">
          <h3>{{ stats.uniqueUsers || 0 }}</h3>
          <p>使用用户数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-money"></i>
        </div>
        <div class="stat-content">
          <h3>¥{{ stats.totalDiscount || 0 }}</h3>
          <p>总优惠金额</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-pie-chart"></i>
        </div>
        <div class="stat-content">
          <h3>¥{{ stats.avgDiscount || 0 }}</h3>
          <p>平均优惠金额</p>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.userId"
            placeholder="请输入用户ID"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="使用类型">
          <el-select v-model="searchForm.usageType" placeholder="请选择使用类型" clearable>
            <el-option label="折扣" value="DISCOUNT"></el-option>
            <el-option label="免邮" value="FREE_SHIPPING"></el-option>
            <el-option label="积分奖励" value="POINTS_BONUS"></el-option>
            <el-option label="优先服务" value="PRIORITY_SERVICE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="有效" value="ACTIVE"></el-option>
            <el-option label="已取消" value="CANCELLED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData" >搜索</el-button>
          <el-button @click="resetSearch" >重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom"></el-table-column>
        <el-table-column prop="userName" label="用户" width="120">
          <template slot-scope="scope">
            <div class="user-info">
              <span>{{ scope.row.userName || scope.row.username }}</span>
              <small>ID: {{ scope.row.userId }}</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="benefitName" label="权益名称" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.benefitName || '会员折扣' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="usageType" label="使用类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getUsageTypeColor(scope.row.usageType)">
              {{ getUsageTypeText(scope.row.usageType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="originalAmount" label="原始金额" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.originalAmount">¥{{ scope.row.originalAmount }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="discountAmount" label="优惠金额" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.discountAmount" class="discount-amount">
              -¥{{ scope.row.discountAmount }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="finalAmount" label="最终金额" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.finalAmount">¥{{ scope.row.finalAmount }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderId" label="订单ID" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.orderId">{{ scope.row.orderId }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="usageDate" label="使用时间" width="180" sortable="custom">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.usageDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'danger'">
              {{ scope.row.status === 'ACTIVE' ? '有效' : '已取消' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="viewDetail(scope.row)"
              type="text"
              icon="el-icon-view"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 'ACTIVE'"
              size="mini"
              @click="cancelUsage(scope.row)"
              type="text"
              icon="el-icon-close"
              style="color: #f56c6c"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="权益使用详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      @close="closeDetailDialog"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="使用ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentDetail.userName || currentDetail.username }}</el-descriptions-item>
          <el-descriptions-item label="权益名称">{{ currentDetail.benefitName || '会员折扣' }}</el-descriptions-item>
          <el-descriptions-item label="使用类型">{{ getUsageTypeText(currentDetail.usageType) }}</el-descriptions-item>
          <el-descriptions-item label="原始金额">
            <span v-if="currentDetail.originalAmount">¥{{ currentDetail.originalAmount }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="优惠金额">
            <span v-if="currentDetail.discountAmount" class="discount-amount">-¥{{ currentDetail.discountAmount }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="最终金额">
            <span v-if="currentDetail.finalAmount">¥{{ currentDetail.finalAmount }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单ID">
            <span v-if="currentDetail.orderId">{{ currentDetail.orderId }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="使用时间">{{ formatDate(currentDetail.usageDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentDetail.status === 'ACTIVE' ? 'success' : 'danger'">
              {{ currentDetail.status === 'ACTIVE' ? '有效' : '已取消' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ currentDetail.description }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BenefitUsage',
  data() {
    return {
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      searchForm: {
        userId: '',
        usageType: '',
        status: ''
      },
      stats: {},
      detailDialogVisible: false,
      currentDetail: null,
      sortField: '',
      sortOrder: ''
    }
  },
  mounted() {
    this.loadData()
    this.loadStats()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        
        if (this.sortField) {
          params.sortField = this.sortField
          params.sortOrder = this.sortOrder
        }
        
        const response = await this.request.get('/api/member/benefit-usage/page', { params })
        if (response.code === '200') {
          this.tableData = response.data.records
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadStats() {
      try {
        const response = await this.request.get('/api/member/benefit-usage/stats')
        if (response.code === '200') {
          this.stats = response.data
        } else {
          this.$message.error(response.msg || '加载统计数据失败')
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    
    searchData() {
      this.currentPage = 1
      this.loadData()
    },
    
    resetSearch() {
      this.searchForm = {
        userId: '',
        usageType: '',
        status: ''
      }
      this.currentPage = 1
      this.loadData()
    },
    
    refreshData() {
      this.loadData()
      this.loadStats()
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    
    handleSortChange({ column, prop, order }) {
      this.sortField = prop
      this.sortOrder = order === 'ascending' ? 'asc' : 'desc'
      this.loadData()
    },
    
    viewDetail(row) {
      this.currentDetail = row
      this.detailDialogVisible = true
    },
    
    closeDetailDialog() {
      this.currentDetail = null
      this.detailDialogVisible = false
    },
    
    async cancelUsage(row) {
      try {
        await this.$confirm('确定要取消此权益使用记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.request.post(`/api/member/benefit-usage/cancel/${row.id}`)
        if (response.code === '200') {
          this.$message.success('取消成功')
          this.loadData()
        } else {
          this.$message.error(response.msg || '取消失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消失败:', error)
          this.$message.error('取消失败')
        }
      }
    },
    
    exportData() {
      // 导出数据功能
      this.$message.info('导出功能开发中...')
    },
    
    getUsageTypeText(type) {
      const typeMap = {
        'DISCOUNT': '折扣',
        'FREE_SHIPPING': '免邮',
        'POINTS_BONUS': '积分奖励',
        'PRIORITY_SERVICE': '优先服务'
      }
      return typeMap[type] || type
    },
    
    getUsageTypeColor(type) {
      const colorMap = {
        'DISCOUNT': 'success',
        'FREE_SHIPPING': 'primary',
        'POINTS_BONUS': 'warning',
        'PRIORITY_SERVICE': 'info'
      }
      return colorMap[type] || 'info'
    },
    
    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.benefit-usage-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-content h3 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.stat-content p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.table-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-info small {
  color: #999;
  font-size: 12px;
}

.discount-amount {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-content {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .benefit-usage-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
}
</style> 